package com.mactivity.database;

import java.sql.Date;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.mactivity.helper.Constants;

public class PlanActivityFunctions {

	/**
	 * insert new individual plan into database
	 * @param type	sport type
	 * @param planDate	planned date
	 * @param time		planned time
	 * @param userID	the user's ID
	 */
	@SuppressWarnings("deprecation")
	public void newIndividualPlan(String type, Date planDate, String time, String userID){
		String response=null;
		
		// map java object into php object
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("sportType", type));
		postParameters.add(new BasicNameValuePair("date",planDate.getYear()+"-"+(planDate.getMonth()+1)+"-"+planDate.getDate()));
		postParameters.add(new BasicNameValuePair("time", time));
		postParameters.add(new BasicNameValuePair("userID", userID));
		
		
		try {
			// insert new individual plan into database
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/plan_activity.php",
					postParameters);
			
			Log.d(Constants.LOG_DATABASE_TAG, "Database response recieved :"+response);
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.d(Constants.LOGGER_ERROR_TAG, "Unable to connect to database");
		}
	}

	/**
	 * before insert new plan into database, check if there is any time conflict with previous individual plan
	 * ( including plan made by user or plan accepted by the user)
	 * @param planDate date of the plan
	 * @param time time of the plan
	 * @param userID user's id
	 */
	@SuppressWarnings("deprecation")
	public boolean checkConflectIndividualTime(Date planDate, String time, String userID){
		String response=null;
		
		// map java object into php object
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("date",planDate.getYear()+"-"+(planDate.getMonth()+1)+"-"+planDate.getDate()));
		postParameters.add(new BasicNameValuePair("time", time));
		postParameters.add(new BasicNameValuePair("userID", userID));
		
		
		try {
			// check if there is a match in the individual plan table
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/check_individual_time_conflict.php",
					postParameters);
			Log.d(Constants.LOG_DATABASE_TAG, "have match in individual plan?:"+response);
			if (response.contains("1"))	// date and time is reserved before
				return true;
			else
				//check return 0, means no reservation on the same date and time, return false
				return false;	


		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.d(Constants.LOGGER_ERROR_TAG, "exception: "+e.toString());
		}
		return true;
	}
	
	/**
	 * before insert new plan into database, check if there is any time conflict with previous created group plan
	 * ( including plan made by user or plan accepted by the user)
	 * @param planDate date of the plan
	 * @param time time of the plan
	 * @param userID user's id
	 */
	@SuppressWarnings("deprecation")
	public boolean checkConflectGroupCreatedTime(Date planDate, String time, String userID){
		String response=null;
		
		// map java object into php object
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("date",planDate.getYear()+"-"+(planDate.getMonth()+1)+"-"+planDate.getDate()));
		postParameters.add(new BasicNameValuePair("time", time));
		postParameters.add(new BasicNameValuePair("userID", userID));
		
		
		try {			
			// check if there is a match in the group plan table
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/check_group_time_conflict.php",
					postParameters);
			Log.d(Constants.LOG_DATABASE_TAG, "have match in group plan?:"+response);
			if(response.contains("1"))	// date and time is reserved before
				return true;
			else
				//check return 0, means no reservation on the same date and time, return false
				return false;	


		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.d(Constants.LOGGER_ERROR_TAG, "exception: "+e.toString());
		}
		return true;
	}
	
	/**
	 * before insert new plan into database, check if there is any time conflict with previous accepted group plan
	 * ( including plan made by user or plan accepted by the user)
	 * @param planDate date of the plan
	 * @param time time of the plan
	 * @param userID user's id
	 */
	@SuppressWarnings("deprecation")
	public boolean checkConflectGroupAcceptedTime(Date planDate, String time, String userID){
		String response=null;
		
		// map java object into php object
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("date",planDate.getYear()+"-"+(planDate.getMonth()+1)+"-"+planDate.getDate()));
		postParameters.add(new BasicNameValuePair("time", time));
		postParameters.add(new BasicNameValuePair("userID", userID));
		
		
		try {			
			// check if there is a match on the accepted group plan
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/check_accepted_group_conflict.php",
					postParameters);
			Log.d(Constants.LOG_DATABASE_TAG, "have match in accepted group plan?:"+response);
			if(response.contains("1"))	// date and time is reserved before
				return true;
			else
				// check return 0, means no reservation on the same date and time, return false
				return false;	


		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.d(Constants.LOGGER_ERROR_TAG, "exception: "+e.toString());
		}
		return true;
	}
		
	/**
	 * insert new group plan into the database
	 * @param type sport type
	 * @param planDate date of the plan
	 * @param time time of the plan
	 * @param userID ID of the user
	 * @return the id of the group
	 */
	@SuppressWarnings("deprecation")
	public String newGroupPlan(String type, Date planDate, String time, String userID){
		String response=null;
		
		// map java object into php object
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("sportType", type));
		postParameters.add(new BasicNameValuePair("date",planDate.getYear()+"-"+(planDate.getMonth()+1)+"-"+planDate.getDate()));
		postParameters.add(new BasicNameValuePair("time", time));
		postParameters.add(new BasicNameValuePair("userID", userID));
		
		
		try {
			// insert the new group plan into database
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/group_activity.php",
					postParameters);
			
			Log.d(Constants.LOG_DATABASE_TAG, "created a new group plan");
			
			// get the id of the new group plan
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/fetch_groupid.php",
					postParameters);
			Log.d(Constants.LOG_DATABASE_TAG, "Database response recieved");
			// get database response 
			JSONArray jArray = new JSONArray(response);
			JSONObject json_data = jArray.getJSONObject(0);
			
			if (json_data!=null)	// if their is a match
				return json_data.getString("GroupPlanId");
			else	// no match
				throw new NullPointerException();
			
			
		} 
		catch(NullPointerException e){
			Log.d(Constants.LOGGER_ERROR_TAG, "can not find the group id");
		}
		catch (Exception e) {
		
			// TODO Auto-generated catch block
			Log.d(Constants.LOGGER_ERROR_TAG, "Unable to connect to database");
		}
		return response;
	}

	/**
	 * insert group invitation into database 
	 * @param invitorID Id of the inviter
	 * @param ReceiverIDList the list of the receivers
	 * @param groupID Id of the group
	 */
	public void sendGroupRequest(String inviterID, ArrayList<String> ReceiverIDList, String groupID){
		String response=null;
		// map java object into php object
		while(!ReceiverIDList.isEmpty()){
			String receiverId = ReceiverIDList.remove(0);
			ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair("myid", inviterID));
			postParameters.add(new BasicNameValuePair("frid",receiverId));
			postParameters.add(new BasicNameValuePair("grpid", groupID));
			
			try {
				// send group plan invitation to each invited member
				response = CustomHttpClient.executeHttpPost(
						"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/invite_friend.php",
						postParameters);
				
				Log.d(Constants.LOG_DATABASE_TAG, "Database response recieved: "+response);			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d(Constants.LOGGER_ERROR_TAG, "Unable to connect to database");
			}
		}
	}

	/**
	 * get the list of friend id 
	 * @param inviterID id of the group plan inviter
	 * @return
	 */
	public String[] getFriendIdList(String inviterID){
		Log.d(Constants.LOG_DATABASE_TAG, "get friend ID List method called");
		String response=null;
		String[] friendIdList=null;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("userId", inviterID));
		try {
			// fetch all friends' id 
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/fetch_friend_id_list.php",
					postParameters);
			Log.d(Constants.LOG_DATABASE_TAG, "Database response recieved: "+response);
			if(response!=null){	// have friend
				
				JSONArray jArray = new JSONArray(response);
				friendIdList = new String[jArray.length()];
				
				for (int i = 0; i < jArray.length(); i++) {
					JSONObject json_data = jArray.getJSONObject(i);
					// user id on friend list table is same as inviter id
					if(String.valueOf(json_data.getInt(Constants.COLUMN_FRIEND_TABLE_USER_ID)).compareTo(inviterID)==0)
						// store friend id from friend table
						friendIdList[i]=String.valueOf(json_data.getInt(Constants.COLUMN_FRIEND_TABLE_FRIEND_ID));
					else	//otherwise, store user id from friend table
						friendIdList[i]=String.valueOf(json_data.getInt(Constants.COLUMN_FRIEND_TABLE_USER_ID));
				}			
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.d(Constants.LOGGER_ERROR_TAG, "Unable to connect to database: "+e.toString());
		}
		return friendIdList;
	}

	/**
	 * get the list of the friend name
	 * @param friendIdList list of the friend id
	 * @return a list of the friend name
	 */
	public String[] getFriendNameList(String[] friendIdList){
		Log.d(Constants.LOG_DATABASE_TAG, "get friend name List method called");
		String response=null;
		String [] friendNameList=null;
		friendNameList= new String[friendIdList.length];
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		// go through id list for each friend name
		for(int i=0; i<friendIdList.length;i++){
			postParameters.add(new BasicNameValuePair("userId", friendIdList[i]));
			try {
				// fetch friends name
				response = CustomHttpClient.executeHttpPost(
						"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/fetch_friend_name.php",
						postParameters);
				Log.d(Constants.LOG_DATABASE_TAG, "Database response recieved: "+response);
					
				JSONArray jArray = new JSONArray(response);
				// get the friend name
				JSONObject json_data = jArray.getJSONObject(0);
				// store the friend name in a list
				friendNameList[i]=String.valueOf(json_data.getString((Constants.COLUMN_USER_NAME)));

				}
			catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d(Constants.LOGGER_ERROR_TAG, "Unable to connect to database: "+e.toString());
			}
		}
		return friendNameList;
	}
	
	/**
	 * get the friend email list
	 * @param friendIdList list of friend id
	 * @return a list of friend email
	 */
	public String[] getFriendEmailList(String[] friendIdList){
		Log.d(Constants.LOG_DATABASE_TAG, "get friend email List method called");
		String response=null;
		String [] friendEmailList=null;
		friendEmailList= new String[friendIdList.length];
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		// go through id list for each friend email
		for(int i=0; i<friendIdList.length;i++){
			postParameters.add(new BasicNameValuePair("userId", friendIdList[i]));
			try {
				// get friend's email
				response = CustomHttpClient.executeHttpPost(
						"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/fetch_friend_email.php",
						postParameters);
				Log.d(Constants.LOG_DATABASE_TAG, "Database response recieved: "+response);
					
				JSONArray jArray = new JSONArray(response);
				// get the friend email
				JSONObject json_data = jArray.getJSONObject(0);
				// store the friend email in a list
				friendEmailList[i]=String.valueOf(json_data.getString((Constants.COLUMN_USER_EMAIL)));

				}
			catch (Exception e) {
				// TODO Auto-generated catch block
				Log.d(Constants.LOGGER_ERROR_TAG, "Unable to connect to database: "+e.toString());
			}
		}
		return friendEmailList;
	}

	/**
	 * get the total number of people attending this sport individually at the certain date and time		
	 * @param type	sport type
	 * @param planDate	date to attend
	 * @param time	time to attend
	 * @return total number of people
	 */
	@SuppressWarnings("deprecation")
	public int getIndividualNum(String type, Date planDate, String time){
		Log.d(Constants.LOG_DATABASE_TAG, "get individual number method called");
		String response=null;
		int num =0;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("sportType", type));
		postParameters.add(new BasicNameValuePair("date",planDate.getYear()+"-"+(planDate.getMonth()+1)+"-"+planDate.getDate()));
		postParameters.add(new BasicNameValuePair("time", time));
		
		try {
			// get total num of people created a individual plan of this sport at the date and time
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/getIndividualNum.php",
					postParameters);
			Log.d(Constants.LOG_DATABASE_TAG, "total individual plan num: "+response);
			response = response.replaceAll("\n", "");
			num = Integer.parseInt(response);	// get how many individual plans match 

		} catch (Exception e) {
			Log.d(Constants.LOGGER_ERROR_TAG, "Unable to connect to database: "+e.toString());
		}
		return num;
	}
	
	/**
	 * get the list of group plan id of specific sport at certain date and time
	 * @param type sport type
	 * @param planDate date to attend
	 * @param time time to attend
	 * @return list of group plan id
	 */
	@SuppressWarnings("deprecation")
	public int[] getGroupIdList(String type, Date planDate, String time){
		Log.d(Constants.LOG_DATABASE_TAG, "get group id list method called");
		String response=null;
		int[] groupIdList = new int[0];
		JSONArray jArray=null;
		
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("sportType", type));
		postParameters.add(new BasicNameValuePair("date",planDate.getYear()+"-"+(planDate.getMonth()+1)+"-"+planDate.getDate()));
		postParameters.add(new BasicNameValuePair("time", time));
		
		try {
			// fetch all group's id 
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/getGroupIdList.php",
					postParameters);
			Log.d(Constants.LOG_DATABASE_TAG, "group id list: "+response);
			if(!response.contains("null")){
				jArray = new JSONArray(response);
				groupIdList = new int[jArray.length()];
				// put all group id into a list
				for (int i = 0; i < jArray.length(); i++) {
					JSONObject json_data = jArray.getJSONObject(i);
					groupIdList[i]= json_data.getInt(Constants.COLUMN_GROUPPLAN_GROUPPLANID);
				}	
			}
						
		}
		catch (Exception e) {
			Log.d(Constants.LOGGER_ERROR_TAG, "Unable to connect to database: "+e.toString());
		}
		return groupIdList;
	}
	
	/**
	 * get the number of people attending the group plan
	 * @param groupId id of the group plan
	 * @return number of people attending
	 */
	public int getGroupAttendingNum(int groupId){
		Log.d(Constants.LOG_DATABASE_TAG, "get group attedning number method called");
		String response=null;
		int num =0;
		
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("GroupPlanId", String.valueOf(groupId)));

		
		try {			
			// 
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/getGroupAcceptedNum.php",
					postParameters);
			Log.d(Constants.LOG_DATABASE_TAG, "attending group plan count: "+response);
			response = response.replaceAll("\n", "");
			num = Integer.parseInt(response);	// number of people attending this group plan 
			

		} catch (Exception e) {
			Log.d(Constants.LOGGER_ERROR_TAG, "Unable to connect to database: "+e.toString());
		}
		return num;
	}

	/**
	 * get the id of the group plan user participates on the same time
	 * @param planDate date of the plan
	 * @param time time of the plan
	 * @param userID user id
	 * @return id of the plan
	 */
	@SuppressWarnings("deprecation")
	public int getGroupPlanIdAtSameTime(Date planDate, String time, String userID){
		String response=null;
		int planId =0;
		
		// map java object into php object
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("date",planDate.getYear()+"-"+(planDate.getMonth()+1)+"-"+planDate.getDate()));
		postParameters.add(new BasicNameValuePair("time", time));
		postParameters.add(new BasicNameValuePair("userID", userID));
		
		
		try {			
			// check if there is a match in the group plan table
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/get_group_plan_created_same_time.php",
					postParameters);
			Log.d(Constants.LOG_DATABASE_TAG, "group plan id at same time:"+response);
			if(!response.contains("null")){
				// get database response 
				JSONArray jArray = new JSONArray(response);
				JSONObject json_data = jArray.getJSONObject(0);
				if(json_data!=null)
					// get the id of the plan
					planId = json_data.getInt(Constants.COLUMN_GROUPPLAN_GROUPPLANID);
			}
			if(planId!=0)// have a match
				return planId;
			else {	// no match group plan on the same time that user created
				response = CustomHttpClient.executeHttpPost(
						"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/get_group_plan_accepted_same_time.php",
						postParameters);
				Log.d(Constants.LOG_DATABASE_TAG, "have match in accepted plan?:"+response);
				if(!response.contains("null")){
					// get database response 
					JSONArray jArray = new JSONArray(response);
					JSONObject json_data = jArray.getJSONObject(0);
					// get the id of the plan
					if(json_data!=null)
						planId = json_data.getInt(Constants.COLUMN_GROUPPLAN_GROUPPLANID);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.d(Constants.LOGGER_ERROR_TAG, "exception: "+e.toString());
		}
		return planId;
	}

	public int getInvitedNum(int groupPlanId) {
		int num=0;
		String response=null;		
		// map java object into php object
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("GroupPlanId", String.valueOf(groupPlanId)));
		
		try {			
			// check if there is a match in the group plan table
			response = CustomHttpClient.executeHttpPost(
					"http://omega.uta.edu/~hbs1966/db_files/PlanActivity/getInvitedNum.php",
					postParameters);
			Log.d(Constants.LOG_DATABASE_TAG, "total invited:"+response);
			if(!response.contains("null")){
				response=response.replaceAll("\n", "");
				num = Integer.parseInt(response);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.d(Constants.LOGGER_ERROR_TAG, "exception: "+e.toString());
		}
		return num;
	}
}

